
from requests import get
from collections import defaultdict
from threading import Lock, Thread
import json

COUNT = 100
global_result = defaultdict(int)
base_url = 'https://api.bilibili.com/x/v2/reply/main?csrf=88bb14d1b2c3e27bba454c80c2054c01&mode=3&oid=989444108&plat=1&type=1&next='
lock = Lock()

def parse(url):
    res = json.loads(get(url).text)
    if res['code'] != 0:
        raise Exception(f'{res["message"]} {res["code"]}')
    return json.loads(get(url).text)

def yarn(page):
    global global_result
    print(f'第{page}页开始')
    result = defaultdict(int)
    content = parse(f'{base_url}{page}')
    for reply in content['data']['replies']:
        result[reply['member']['level_info']['current_level']] += 1
        if reply['replies']:
            for lzl in reply['replies']:
                result[lzl['member']['level_info']['current_level']] += 1
    print(f'第{page}页结束')
    lock.acquire()
    for k, v in result.items():
        global_result[k] += v
    lock.release()
    print(f'第{page}页写入完成')

def run(start):
    tasks = []
    for i in range(start, start + COUNT if start + COUNT < total else total):
        tasks.append(Thread(target=yarn, args=(i, )))
        tasks[-1].start()
    for i in tasks:
        i.join()

def get_total():
    return parse(base_url)['data']['cursor']['all_count']

def print_result():
    for k, v in global_result.items():
        print(f'Level{k}: {v}')

if __name__ == '__main__':
    total = get_total()
    print(f'总页数:{total}')
    for i in range(0, total, COUNT):
        run(i)
    print_result()